package com.thinkingstar.iads.projectcenter.jsoup.api;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import com.thinkingstar.iads.common.utils.FileCommonUtil;
import com.thinkingstar.iads.common.utils.HtmlPropertiesForSjps;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler.referenceInsertExecutor;
import org.apache.xmlbeans.impl.xb.xsdschema.impl.PublicImpl;
import org.eclipse.jetty.client.api.Request;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.castor.castor.String2BigDecimal;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;

import com.thinkingstar.iads.common.utils.InitSystemProperties;
import com.thinkingstar.iads.common.utils.POIFileUtil;
import com.thinkingstar.iads.common.utils.StringUtil;
import com.thinkingstar.iads.cs.sys.enumerate.WIDGET_TYPE;
import com.thinkingstar.iads.datacenter.entity.DcProjectFieldWidget;
import com.thinkingstar.iads.projectcenter.entity.PcProjectFile;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectFile;
import com.thinkingstar.iads.projectcenter.serviceImpl.PreviewFileServiceImpl;

import org.springframework.util.ClassUtils;

/**
 * java操作html相关
 * @author Administrator
 */
@IocBean
public class JsoupElementServiceImpl {
	
	@Inject
	private DaoPcProjectFile daoPcProjectFile;
	
	@Inject
	private PreviewFileServiceImpl previewFileServiceImpl;
	
	private final Document getDocument(){
		String html = InitSystemProperties.getHtmlTemplate();
		Document document = Jsoup.parseBodyFragment(html);
		return document;
	}

	private final Document getDocumentForSjps(){
		String html = HtmlPropertiesForSjps.getHtmlTemplate();
		Document document = Jsoup.parseBodyFragment(html);
		return document;
	}
	
	private static final Element getOptionElement(){
		String option_html = "<option value=''></option>";
		Document document = Jsoup.parse(option_html);
		Element element =document.getElementsByTag("option").first();
		return element;
	}
	
	private static final Element getCheckboxElement(){
		String checkbox_html = "<input name='' title='' type='checkbox'>";
		Document document = Jsoup.parse(checkbox_html);
		Element element = document.getElementsByTag("input").first();
		return element;
	}
	
	//获取动态表单文档节点
	public String getElementForForm(List <DcProjectFieldWidget> widgets , NutMap data_map , HttpServletRequest request) throws IOException{
		StringBuilder result_html = new StringBuilder();
		for(DcProjectFieldWidget widget : widgets){
			String field_name = widget.getField_name(); //字段名称
			String field_comment = widget.getField_comment();//字段备注
			String widget_type = widget.getWidget_type();//控件类型
			String default_value = widget.getDefault_value(); //控件默认值
			String widget_length = widget.getWidget_length();
			if(WIDGET_TYPE.下拉选.getCode().equals(widget_type)){
				Element select_element = getDocument().getElementsByAttributeValue("data_id","select").first();
				select_element.child(0).text(field_comment);
				select_element.child(1).children().first().attr("name", field_name).attr("lay-filter", field_name);
				//默认值
				String [] default_values = default_value.split(",");
				String option_elements = "";
				for(int i=0;i<default_values.length;i++){
					Element option_element = getOptionElement().val(default_values[i]).text(default_values[i]);
					if(StringUtils.isNotBlank(data_map.getString(field_name)) && data_map.getString(field_name).trim().equals(default_values[i].trim())){
						//默认选择
						option_element.attr("selected", "selected");
					}
					option_elements += option_element.toString();
				}
				select_element.child(1).children().first().append(option_elements);
				result_html.append(select_element.toString());
			}else if(WIDGET_TYPE.行内文本.getCode().equals(widget_type)){
				Element inline_text_element = getDocument().getElementsByAttributeValue("data_id", "inline_text").first();
				inline_text_element.child(0).text(field_comment);
				inline_text_element.child(1).children().first().attr("name", field_name).attr("lay-verify", field_name).val(data_map.getString(field_name)==null?"":data_map.getString(field_name));
				result_html.append(inline_text_element.toString());
			}else if(WIDGET_TYPE.行内文本域.getCode().equals(widget_type)){
				Element inline_textarea_element = getDocument().getElementsByAttributeValue("data_id", "inline_textarea").first();
				inline_textarea_element.child(0).text(field_comment);
				inline_textarea_element.child(1).children().first().attr("name", field_name).text(data_map.getString(field_name)==null?"":data_map.getString(field_name));
				result_html.append(inline_textarea_element.toString());
			}else if(WIDGET_TYPE.复合单选框.getCode().equals(widget_type)){
				//默认值
				Element radio_element = getDocument().getElementsByAttributeValue("data_id", "radio").first();
				radio_element.child(0).text(field_comment);
				radio_element.child(1).children().first().attr("name", field_name).attr("lay-filter", field_name).attr("lay-text", "是|否");
				if(StringUtils.isNotBlank(data_map.getString(field_name)) && data_map.getString(field_name).equals("on")){
					radio_element.child(1).children().first().attr("checked", "");
				}
				result_html.append(radio_element.toString());
			}else if(WIDGET_TYPE.复合多选框.getCode().equals(widget_type)){
				Element checkbox_element = getDocument().getElementsByAttributeValue("data_id", "checkbox").first();
				checkbox_element.child(0).text(field_comment);
				String [] default_values = default_value.split(",");
				String input_elements = "";
				for(int i=0;i<default_values.length;i++){
					String default_value_str = default_values[i];
					Element checkbox_input_element = getCheckboxElement();
					checkbox_input_element.attr("name", field_name).attr("title", default_value_str);
					if(StringUtils.isNotBlank(data_map.getString(field_name)) && data_map.getString(field_name).indexOf(default_value_str) > -1){
						checkbox_input_element.attr("checked", "");
					}
					input_elements += checkbox_input_element.toString();
				}
				checkbox_element.child(1).append(input_elements);
				result_html.append(checkbox_element.toString());
			}else if(WIDGET_TYPE.结构化图片.getCode().equals(widget_type)){
				Element image_element = getDocument().getElementsByAttributeValue("data_id", "image_div").first();
				image_element.child(0).text(field_comment);
				String value = data_map.getString(field_name)==null?"":data_map.getString(field_name);
				image_element.child(1).attr("lay-title","图片上传").attr("name", "file").attr("data_id", field_name).attr("file_type", WIDGET_TYPE.结构化图片.getCode());
				image_element.child(2).children().get(0).attr("src", request.getContextPath()+"/datacenter/common/getFileById?file_id="+value).attr("data_id", field_name);
				image_element.child(2).children().get(1).attr("name", field_name).val(value);
				result_html.append(image_element.toString());
			}
		}
		return result_html.toString();
	}

	//获取文档节点
	public String getElement(List <DcProjectFieldWidget> widgets , NutMap data_map , HttpServletRequest request) throws IOException{
		StringBuilder result_html = new StringBuilder();
		Element btn_element = getDocument().getElementsByAttributeValue("data_id", "btn").first();
		Element no_btn_element = getDocument().getElementsByAttributeValue("data_id" ,"no_btn").first();
		for(DcProjectFieldWidget widget : widgets){
			String field_name = widget.getField_name();//字段名称
			String field_comment = widget.getField_comment();//字段备注
			Boolean is_show = widget.getIs_show();//是否在页面上显示该元素
			String widget_type = widget.getWidget_type();//控件类别
			String widget_length = widget.getWidget_length();//控件长度
			if(is_show){
				if(WIDGET_TYPE.文本域.getCode().equals(widget_type)){
					Element textarea_element = getDocument().getElementsByAttributeValue("data_id","textarea").first();
					no_btn_element.child(0).text(field_comment);
					textarea_element.child(0).attr("name", field_name).val(StringUtils.isBlank(data_map.getString(field_name))?"":data_map.getString(field_name));
					String text_html = no_btn_element.toString()+textarea_element.toString();
					result_html.append(text_html);
				}else if(WIDGET_TYPE.图片.getCode().equals(widget_type)){
					Element image_element = getDocument().getElementsByAttributeValue("data_id","image").first();
					String field_value = StringUtils.isBlank(data_map.getString(field_name))?"":data_map.getString(field_name);
					//image_element.child(0).attr("id", field_name).attr("src", request.getContextPath()+"/datacenter/common/getFileById?file_id="+field_value);
					image_element.child(0).attr("name", field_name).attr("value", field_value);
					image_element.child(1).attr("data_id", field_value).attr("src", previewFileServiceImpl.getUrl(field_value,request));
					btn_element.child(0).text(field_comment);
					btn_element.child(1).attr("lay-title","图片上传").attr("name", "file").attr("data_id", field_name).attr("file_type", WIDGET_TYPE.图片.getCode());
					btn_element.child(2).attr("download_path", field_value).text("下载文件");
					//btn_element.child(3).attr("preview_path",field_value).text("在线预览");
					String image_html = btn_element.toString() + image_element.toString();
					result_html.append(image_html);
				}else if(WIDGET_TYPE.getWidgetTypeByCode(widget_type) != null){//普通文件表单
					WIDGET_TYPE widget_TYPE = WIDGET_TYPE.getWidgetTypeByCode(widget_type);
					Element _element = getDocument().getElementsByAttributeValue("data_id", widget_type).first();
					String field_value = StringUtils.isBlank(data_map.getString(field_name))?"":data_map.getString(field_name); //字段属性
					PcProjectFile file_obj = daoPcProjectFile.fetch(field_value);
					String file_path = "";
					String file_name = "";
					if(file_obj != null){
						file_path = file_obj.getRelativePaths();
						file_name = file_obj.getName();
					}
					_element.child(0).attr("name",field_name).attr("value",field_value);
					_element.child(1).attr("data_id", field_name).attr("src", previewFileServiceImpl.getUrl(field_value,request));
					btn_element.child(0).text(field_comment);
					btn_element.child(1).attr("lay-title",widget_type+"上传").attr("name", "file").attr("data_id", field_name).attr("file_type", widget_TYPE.getCode());
					btn_element.child(2).attr("download_path", field_value).text("下载文件"); //文件id
					//btn_element.child(3).attr("preview_path",field_value).text("在线预览"); //文件id
					String excel_html = btn_element.toString() + _element.toString();
					result_html.append(excel_html);
				}
			}
		}
		return result_html.toString();
	}

	
	//获取自定义表单
	public String getDiyHtml(List <DcProjectFieldWidget> widgets , NutMap data_map , String project_id , HttpServletRequest request) throws IOException{
		Element content_element = getDocument().getElementsByAttributeValue("data_id","content").first();
		Element submit_element = getDocument().getElementsByAttributeValue("data_id","submit_btn").first();
		Element id_element = getDocument().getElementsByAttributeValue("name","id").first();
		Element project_id_element = getDocument().getElementsByAttributeValue("name","project_id").first();
		project_id_element.val(project_id);
		id_element.val(StringUtils.isBlank(data_map.getString("id"))?"":data_map.getString("id"));
		submit_element.child(0).text("保存资料");
		String result_html = getElement(widgets,data_map,request);
		content_element.append(result_html).append(id_element.toString()).append(project_id_element.toString()).append(submit_element.toString());
		return content_element.toString();
	}
	
	//获取结构化特殊表单
	public String getDiyHtmlForForm(List <DcProjectFieldWidget> widgets , NutMap data_map , String project_id , HttpServletRequest request) throws IOException{
		Element content_element = getDocument().getElementsByAttributeValue("data_id","content").first();
		Element submit_element = getDocument().getElementsByAttributeValue("data_id","submit_btn").first();
		Element id_element = getDocument().getElementsByAttributeValue("name","id").first();
		Element project_id_element = getDocument().getElementsByAttributeValue("name","project_id").first();
		project_id_element.val(project_id);
		id_element.val(StringUtils.isBlank(data_map.getString("id"))?"":data_map.getString("id"));
		submit_element.child(0).text("保存资料");
		String result_html = getElementForForm(widgets,data_map,request);
		content_element.append(result_html).append(id_element.toString()).append(project_id_element.toString()).append(submit_element.toString());
		return content_element.toString();
	}

	//获取自定义表单 只看 设计评审
	public String getDiyHtmlForSjps(List <DcProjectFieldWidget> widgets , NutMap data_map , String project_id , HttpServletRequest request) throws IOException{
		Element content_element = getDocumentForSjps().getElementsByAttributeValue("data_id","content").first();
		//Element submit_element = getDocument().getElementsByAttributeValue("data_id","submit_btn").first();
		Element id_element = getDocumentForSjps().getElementsByAttributeValue("name","id").first();
		Element project_id_element = getDocumentForSjps().getElementsByAttributeValue("name","project_id").first();
		project_id_element.val(project_id);
		id_element.val(StringUtils.isBlank(data_map.getString("id"))?"":data_map.getString("id"));
		//submit_element.child(0).text("保存资料");
		String result_html = getElementForSjps(widgets,data_map,request);
		content_element.append(result_html).append(id_element.toString()).append(project_id_element.toString());//.append(submit_element.toString());
		return content_element.toString();
	}

	//获取文档节点 只看 设计评审
	public String getElementForSjps(List <DcProjectFieldWidget> widgets , NutMap data_map , HttpServletRequest request) throws IOException{
		StringBuilder result_html = new StringBuilder();
		Element btn_element = getDocumentForSjps().getElementsByAttributeValue("data_id", "btn").first();
		Element no_btn_element = getDocumentForSjps().getElementsByAttributeValue("data_id" ,"no_btn").first();
		for(DcProjectFieldWidget widget : widgets){
			String field_name = widget.getField_name();//字段名称
			String field_comment = widget.getField_comment();//字段备注
			Boolean is_show = widget.getIs_show();//是否在页面上显示该元素
			String widget_type = widget.getWidget_type();//控件类别
			String widget_length = widget.getWidget_length();//控件长度
			if(is_show){
				if(WIDGET_TYPE.文本域.getCode().equals(widget_type)){
					Element textarea_element = getDocumentForSjps().getElementsByAttributeValue("data_id","textarea").first();
					no_btn_element.child(0).text(field_comment);
					textarea_element.child(0).attr("name", field_name).val(StringUtils.isBlank(data_map.getString(field_name))?"":data_map.getString(field_name));
					String text_html = no_btn_element.toString()+textarea_element.toString();
					result_html.append(text_html);
				}else if(WIDGET_TYPE.图片.getCode().equals(widget_type)){
					Element image_element = getDocumentForSjps().getElementsByAttributeValue("data_id","image").first();
					String field_value = StringUtils.isBlank(data_map.getString(field_name))?"":data_map.getString(field_name);
					image_element.child(0).attr("name", field_name).attr("value", field_value);
					image_element.child(1).attr("data_id", field_value).attr("src", previewFileServiceImpl.getUrl(field_value,request));
					btn_element.child(0).text(field_comment);
					btn_element.child(1).attr("download_path", field_value).text("下载文件");
					//btn_element.child(2).attr("preview_path",field_value).text("在线预览");
					String image_html = btn_element.toString() + image_element.toString();
					result_html.append(image_html);
				}else if(WIDGET_TYPE.getWidgetTypeByCode(widget_type) != null){//普通文件表单
					WIDGET_TYPE widget_TYPE = WIDGET_TYPE.getWidgetTypeByCode(widget_type);
					Element _element = getDocumentForSjps().getElementsByAttributeValue("data_id", widget_type).first();
					String field_value = StringUtils.isBlank(data_map.getString(field_name))?"":data_map.getString(field_name); //字段属性
					PcProjectFile file_obj = daoPcProjectFile.fetch(field_value);
					String file_path = "";
					String file_name = "";
					if(file_obj != null){
						file_path = file_obj.getRelativePaths();
						file_name = file_obj.getName();
					}
					_element.child(0).attr("name",field_name).attr("value",field_value);
					_element.child(1).attr("data_id", field_value).attr("src", previewFileServiceImpl.getUrl(field_value,request));
					btn_element.child(0).text(field_comment);
//					btn_element.child(1).attr("lay-title",widget_type+"上传").attr("name", "file").attr("data_id", field_name).attr("file_type", widget_TYPE.getCode());
					btn_element.child(1).attr("download_path", field_value).text("下载文件"); //文件id
					//btn_element.child(2).attr("preview_path",field_value).text("在线预览"); //文件id
					String excel_html = btn_element.toString() + _element.toString();
					result_html.append(excel_html);
				}
			}
		}
		return result_html.toString();
	}
}
